package com.rescueworkers.Db;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.fg114.main.service.MyLocation;
import com.fg114.main.util.ActivityUtil;
import com.rescueworkers.Settings;
import com.rescueworkers.dto.Task;
import com.rescueworkers.dto.UploadVoiceOrImageInfo;

/**
 * @author Administrator
 *
 */
public class TaskDb {

	/**
	 * 只进行新数据插入操作
	 */
	public static boolean saveNotFinishTask(Task task) {
		boolean success = false;
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		if (task == null) {
			return false;
		}
		if (getTaskById(task.id) != null) {
			// 如果本地存在此task的相关数据，以本地数据为准
			success = true;
		} else {
			try {
				task.uploadFlag = 1;
				db.insertOrThrow("taskInfo", null, task.fromData());
				success = true;
			} catch (Exception e) {
				e.printStackTrace();
				success = false;
			}
		}
		return success;
	}

	/**
	 * 根据id获取task
	 * 
	 * @param id
	 * @return
	 */
	private static Task getTaskById(String id) {
		Task task = null;
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		Cursor cursor = db.query("taskInfo", null, "id = ?",
				new String[] { id }, null, null, null);
		try {
			if (cursor != null && cursor.getCount() > 0) {
				if (cursor.moveToNext()) {
					task = new Task();
					task.fromCusor(cursor);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return task;
	}

	public static List<Task> getAllTaskList(String uploadFlag) {

		List<Task> taskList = new ArrayList<Task>();
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		Cursor cursor = db.query("taskInfo", null, "uploadFlag = ?",
				new String[] { uploadFlag }, null, null, null);
		try {
			if (cursor != null && cursor.getCount() > 0) {
				while (cursor.moveToNext()) {
					Task task = new Task();
					task.fromCusor(cursor);
					taskList.add(task);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return taskList;

	}

	public static List<Task> getTaskList(String status, String status1 ,int uploadFlag ) {

		List<Task> taskList = new ArrayList<Task>();
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		Cursor cursor = db.query("taskInfo", null, "(status = ? or status = ?) and uploadFlag = ?",
				new String[] { status ,status1,String.valueOf(uploadFlag)}, null, null, null);
		try {
			if (cursor != null && cursor.getCount() > 0) {
				while (cursor.moveToNext()) {
					Task task = new Task();
					task.fromCusor(cursor);
					taskList.add(task);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return taskList;

	}

	/**
	 * 获取未完成或未上传成功的task
	 * 
	 * @param status
	 * @param cancelStatus
	 * @param uploadFlag
	 * @return
	 */
	public static List<Task> getNotFinishOrNotUploadTaskList(String status,
			String cancelStatus, String uploadFlag) {

		List<Task> taskList = new ArrayList<Task>();
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		Cursor cursor = db.query("taskInfo", null,
				"(status != ? and status != ?) or uploadFlag = ?",
				new String[] { status, cancelStatus, uploadFlag }, null, null,
				null);
		try {
			if (cursor != null && cursor.getCount() > 0) {
				while (cursor.moveToNext()) {
					Task task = new Task();
					task.fromCusor(cursor);
					taskList.add(task);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return taskList;

	}

	/**
	 * 更新taskInfo表
	 * 
	 * @param taskId
	 * @param status
	 */
	public static void updateTaskInfo(String taskId, ContentValues values) {
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		db.update("taskInfo", values, " id = ?", new String[] { taskId });
	}

	public static void updateTaskInfo(String taskId, String status,
			String uploadFlag) {
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("status", status);
		values.put("uploadFlag", uploadFlag);
		db.update("taskInfo", values, " id = ?", new String[] { taskId });
	}

	public static void updateTaskUploadInfo(String taskId, String uuid,
			String uploadFlag) {
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("uploadFlag", uploadFlag);
		db.update("taskInfo", values, " id = ? and _id = ?", new String[] {
				taskId, uuid });
	}

	/**
	 * 加入状态更新同步表中
	 * 
	 * @param task
	 * @return
	 */
	public static boolean addIntoTaskUploadInfo(ContentValues values) {

		boolean success = false;
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		if (values == null) {
			return false;
		}
		try {
			db.insertOrThrow("taskUploadInfo", null, values);
			success = true;
		} catch (Exception e) {
			e.printStackTrace();
			success = false;
		}
		return success;

	}

	public static List<Task> getUnUploadTaskList(String uploadFlag) {

		List<Task> taskList = new ArrayList<Task>();
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		Cursor cursor = db.query("taskUploadInfo", null, "uploadFlag = ?",
				new String[] { uploadFlag }, null, null, null);
		try {
			if (cursor != null && cursor.getCount() > 0) {
				if (cursor.moveToNext()) {
					Task task = new Task();
					task.fromCusor(cursor);
					taskList.add(task);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return taskList;

	}

	/**
	 * 获取未上传任务列表
	 * 
	 * @param uploadFlag
	 * @return
	 */
	public static String getUnUploadTask(String uploadFlag) {

		Task task = null;
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		Cursor cursor = db.query("taskUploadInfo", null, "uploadFlag = ?",
				new String[] { uploadFlag }, null, null, null);
		JSONArray jsonArray = new JSONArray();
		try {
			if (cursor != null && cursor.getCount() > 0) {
				while (cursor.moveToNext()) {
					task = new Task();
					task.fromCusor(cursor);
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("latitude", cursor.getString(14));
					jsonObject.put("longitude", cursor.getString(15));
					jsonObject.put("id", cursor.getString(2));
					jsonObject.put("uuid", cursor.getString(1));
					jsonObject.put("state",
							getStateStringFromStatus(cursor.getString(11)));
					jsonObject.put("acquisition_at", cursor.getLong(13));
					jsonObject.put("primary_id", cursor.getString(0));
					jsonArray.put(jsonObject);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return jsonArray.toString();

	}

	/**
	 * 根据状态值转换
	 * 
	 * @param status
	 * @return
	 */
	private static String getStateStringFromStatus(String status) {
		String state = "";
		try {
			if ("已出发".equals(status)) {
				state = "departure";
			} else if ("已到达".equals(status)) {
				state = "arrive";
			} else if ("已完成".equals(status)) {
				state = "complete";
			} else if ("已取消".equals(status)) {
				state = "cancel";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return state;
	}

	public static boolean saveVoiceOrImageInfo(Task task, int type,
			String uuid, String path, String latitude, String longitude,
			String acquisition_at) {
		boolean saveSuccess = false;
		try {
			SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
			ContentValues values = new ContentValues();
			values.put("uuid", uuid);
			values.put("id", task.id);
			values.put("no", task.no);
			values.put("type", type);
			values.put("latitude", latitude);
			values.put("longitude", longitude);
			values.put("acquisition_at", acquisition_at);
			values.put("path", path);
			values.put("uploadFlag", "0");
			db.insert("taskImageOrVoiceInfo", null, values);
			saveSuccess = true;
		} catch (Exception e) {
			e.printStackTrace();
			saveSuccess = false;
		}
		return saveSuccess;
	}
	public static boolean saveVoiceOrImageInfo(UploadVoiceOrImageInfo info) {
		boolean saveSuccess = false;
		try {
			if(info == null ){
				return saveSuccess;
			}
			SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
			ContentValues values = info.fromData();
			db.insert("taskImageOrVoiceInfo", null, values);
			saveSuccess = true;
		} catch (Exception e) {
			e.printStackTrace();
			saveSuccess = false;
		}
		return saveSuccess;
	}

	/*
	 * 删除录音和照片表中的某条数据
	 * 
	 * @param uuid
	 */
	public static void deleteVoiceOrImageFromDb(String uuid) {
		try {
			SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
			db.delete("taskImageOrVoiceInfo", "uuid = ? ",
					new String[] { uuid });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取单条未上传的录音或者图片信息
	 * 
	 * @param uploadFlag
	 * @return
	 */
	public static UploadVoiceOrImageInfo getUnUplaodVoiceOrImage(
			String uploadFlag) {

		UploadVoiceOrImageInfo task = null;
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		Cursor cursor = db
				.query("taskImageOrVoiceInfo", null, "uploadFlag = ?",
						new String[] { uploadFlag }, null, null, null);
		try {
			if (cursor != null && cursor.getCount() > 0) {
				while (cursor.moveToNext()) {
					task = new UploadVoiceOrImageInfo();
					task.fromCusor(cursor);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return task;

	}

	/**
	 * 更新语音和图片信息
	 * 
	 * @param taskId
	 * @param uuid
	 * @param uploadFlag
	 */
	public static void updateUploadVoiceOrImageInfo(String taskId, String uuid,
			String uploadFlag) {
		SQLiteDatabase db = Settings.dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("uploadFlag", uploadFlag);
		db.update("taskImageOrVoiceInfo", values, " id = ? and uuid =  ?",
				new String[] { taskId, uuid });
	}

	public static UploadVoiceOrImageInfo combineVoiceOrImageInfo(Task task , List<UploadVoiceOrImageInfo> imageList,String path,String fileName,int type,int recordTime) {
		MyLocation myLocation = MyLocation.getInstance();
		String latitude = "";
		String longitude = "";
		String locationTime = "";
		if (myLocation != null) {
			latitude = myLocation.getLatitude() + "";
			longitude = myLocation.getLongitude() + "";
			locationTime = myLocation.getLocationTime();
		}
		// 将图片信息保存到数据库
		final String uuid = ActivityUtil.generateUuid();
		UploadVoiceOrImageInfo voiceOrImageInfo = new UploadVoiceOrImageInfo();
		voiceOrImageInfo.setId(task.id);
		voiceOrImageInfo.setNo(task.no);
		voiceOrImageInfo.setUuid(uuid);
		voiceOrImageInfo.setPath(path);
		voiceOrImageInfo.setType(type);
		voiceOrImageInfo.setLatitude(latitude);
		voiceOrImageInfo.setLongitude(longitude);
		voiceOrImageInfo.setAcquisition_at(System.currentTimeMillis());
		voiceOrImageInfo.setRecordTime(recordTime);
		voiceOrImageInfo.setUploadFlag(0);
		voiceOrImageInfo.setFileName(fileName);
		imageList.add(voiceOrImageInfo);
		return voiceOrImageInfo;
	}

}
